package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enumhandler.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: Bytezero_zhengLei
 * @Date: 2024/7/25 12:34
 * @Project_Name:
 * @Email: 420498246@qq.com
 * @Description:
 * @TODO:
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public void updateMoney(Long id, Integer money) {
        //1.查询用户
        User user = this.getById(id);

        //2.校验用户银行卡的状态
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("账号有问题！");
        }


        //3.校验余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("余额不足！");
        }

        //4.没有任何问题，减去
//        userMapper.updateMoney(id,money);


        lambdaUpdate()
                .set(User::getBalance, user.getBalance() - money)
                .set(user.getBalance() - money == 0, User::getStatus, UserStatus.FREEZE)
                .eq(User::getId, id)
                .update();


    }

    @Override
    public List<User> selectUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        List<User> users = this.lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
        return users;


    }

    @Override
    public UserVO getUserAndAddress(Long id) {
        //根据id获取用户对象
        User user = this.getById(id);  //po

        //2.获取用户对应的地址
        List<Address> addresses = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();

        //封装vo
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //给userVo设置地址
        userVO.setAddressVO(BeanUtil.copyToList(addresses, AddressVO.class));



        return userVO;
    }
}
